package cn.bugDance.trigger.job;

import cn.bugDance.domain.activity.model.valobj.ActivitySkuStockSubtractionJobData;
import cn.bugDance.domain.activity.service.quota.IRaffleActivityQuotaService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ActivitySkuQuotaSubtractionJob {

    @Resource
    private IRaffleActivityQuotaService raffleActivityQuotaService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private RedissonClient redissonClient;


    @Scheduled(cron = "0/5 * * * * ?")
    public void exec(){
        RLock lock = redissonClient.getLock("big-market-UpdateActivitySkuStockJob");
        boolean result = false;
        try{
            result = lock.tryLock(3, 3, TimeUnit.SECONDS);
            if(!result) return;
            List<Long> skus = raffleActivityQuotaService.queryActivitySkuList();
            if(skus == null || skus.isEmpty()) return;
            for(Long sku : skus){
                threadPoolExecutor.execute(() -> {
                    try{
                        ActivitySkuStockSubtractionJobData activitySkuStockSubtractionJobData = raffleActivityQuotaService.takeJobQueue(sku);
                        if(activitySkuStockSubtractionJobData == null) return;

                        raffleActivityQuotaService.activitySkuStockSubtractQuota(sku);
                        log.info("【触发层--ActivitySkuQuotaSubtractionJob】: 扣减sku库存成功, sku: {}", sku);
                    }catch (Exception e){
                        log.warn("【触发层--ActivitySkuQuotaSubtractionJob】: 执行sku库存更新任务异常, sku: {}", sku);
                    }
                });
            }
        }catch (Exception e){
            log.warn("【触发层--ActivitySkuQuotaSubtractionJob】: 执行sku库存更新任务失败");
        }
    }
}
